<template>
  <a-badge
    :count="messageCount"
    :number-style="{ backgroundColor: '#F59A23' }"
    :offset="[-2, 20]"
    style="margin-right: 20px; height: 100%;"
    class="mgBadge"
    @click="jumpRoter({path: '/matters/list/todo',title:'待办事项'})"
  >
    <BaseSvgIcon
      class="messageIcon"
      icon="bell"
      color="red"
    />
  </a-badge>
</template>

<script>
import { mapState } from 'vuex'
import Vue from 'vue'
import { messageCountNum } from '@/api/messageSend'
import { getTodoTotal } from '@/api/process'
import { postChangeLog } from '@/mixin/mixin'
import { getProcessParams, getBusinessTodoList } from '@/api/commons'
import { getSelfAudit } from '@/api/indexPage'
import BaseSvgIcon from '@/components/BaseSvgIcon'
export default {
  mixins: [postChangeLog],
  name: 'MessageIcon',
  components: {
    BaseSvgIcon
  },

  data() {
    return {
      timeLoop: 1000 * 60 * 5,
      timerTR: null,
      timerTD: null
    }
  },
  computed: {
    activeTD() {
      return this.$route.name === 'mattersListTodo'
    },
    activeTR() {
      return this.$route.name === 'mattersNewsTo'
    },
    messageCount() {
      return Number(this.$store.getters['messageInfo/GET_TODOCOUNT']) + Number(this.$store.getters['messageInfo/GET_TOREADCOUNT'])
    }
  },
  watch: {
    '$route.name': function (newVal, oldVal) {
      if (newVal === 'mattersListTodo') {
        this.clearTimer('timerTD')
        if (this.timerTR === null) {
          this.getMessageCount()
        }
      } else if (newVal === 'mattersNewsTo') {
        this.clearTimer('timerTR')
        if (this.timerTD === null) {
          this.getTodoTotal()
        }
      } else {
        if (this.timerTD === null) {
          this.getTodoTotal()
        }
        // if (this.timerTR === null) {
        //   this.getMessageCount()
        // }
      }
    }
  },
  beforeDestroy() {
    this.clearTimer('timerTR')
    this.clearTimer('timerTD')
  },
  destroyed() {
    this.clearTimer('timerTR')
    this.clearTimer('timerTD')
  },
  created() {
    this.getMessageCount()
    this.getTodoTotal()
    /**
     * 获取岗位变更一周内数量
     **/
    this.handleGetPostsChangeLog()
  },
  methods: {
    //跳转路由  缓存数据
    jumpRoter(val){
      // sessionStorage.setItem("orginHomeUrl", JSON.stringify(val))
      val = { ...val, codes: ['pece','pece_dbsx','pece_dbsx_sxgl','pece_dbsx_sxgl_dbsx'] }
      this.$storageSet('tabs', [val])
      this.$storageSet('tabs-activeKey', 1)
      this.$store.commit('SET_ACTIVE_CODES', ['pece','pece_dbsx','pece_dbsx_sxgl','pece_dbsx_sxgl_dbsx'])
      this.$router.push(val)
    },
    clearTimer(timer) {
      if (this[timer]) {
        clearTimeout(this[timer])
        this[timer] = null
      }
    },
    toDoLoop() {
      if (this.activeTD) return
      this.clearTimer('timerTD')
      this.timerTD = setTimeout(() => {
        this.getTodoTotal()
      }, this.timeLoop)
    },
    toReadLoop() {
      if (this.activeTR) return
      this.clearTimer('timerTR')
      this.timerTR = setTimeout(() => {
        this.getMessageCount()
      }, this.timeLoop)
    },
    async getTodoTotal() {
      try {
        const userInfo = Vue.getAcloudProvider().getUserInfo()
        let users = []
        // 查询参数限制权限为账号所有的岗位及登录用户id
        if (userInfo?.employee?.posts) {
          users = users.concat(userInfo.employee.posts.map((item) => item.id))
        }
        users.push(userInfo.id)
        let processRes = {}
        try {
          processRes = await getProcessParams()
        } catch (e) {
          // console.error(e)
        }
        if (processRes.data) {
          users = users.concat(processRes.data)
        }
        const params = {
          users: users
        }
        const res = await getTodoTotal(params)
        if (res.code === 200) {
          let num = 0
          const list = res.data || []
          list.forEach((item) => {
            if (item.nums && !isNaN(Number(item.nums))) num += Number(item.nums)
          })
          // console.log(num)
          this.$store.commit('messageInfo/SET_TODOCOUNT', num)
          this.toDoLoop()
          // 业务待办
          getBusinessTodoList({ query: { receiverId: userInfo.id, status: 0 } }).then((res) => {
            const totalNum = (res.totalSize || 0) + num
            this.$store.commit('messageInfo/SET_TODOCOUNT', totalNum)
          })
          // 我发起的
          getSelfAudit({ startUserId: userInfo.id, run: 0 }).then((res) => {
            const totalNum = (res.totalSize || 0) + num
            this.$store.commit('messageInfo/SET_DONECOUNT', totalNum)
          })
        }
      } catch (e) {
        // console.error(e)
      }
    },
    getMessageCount() {
      const param = {
        hasRead: false
      }
      messageCountNum(param).then((res) => {
        if (res.code == '200') {
          let count = isNaN(Number(res.data.countNum)) ? 0 : Number(res.data.countNum)
          // console.log(count)
          this.$store.commit('messageInfo/SET_TOREADCOUNT', count)
          this.toReadLoop()
        }
      })
    }
  }
}
</script>
<style lang="less">
.mgBadge {
  cursor: pointer;
  margin-right: 20px;
  display: flex !important;
  align-items: center;
}
.messageIcon {
  font-size: 24px;
  line-height: 55px;
  // margin-right: 20px;
}
</style>
